//
//  LoginViewController.m
//  OSChina
//
//  Created by 8b410-2 on 16/12/29.
//  Copyright © 2016年 abb. All rights reserved.
//

#import "OSCLoginViewController.h"
#import "OSCOAuthViewModel.h"
#import <SDWebImage/UIImageView+WebCache.h>
#define js_email @"f_email"
#define js_password @"f_pwd"
#define js_captcha @"f_vcode"
@interface OSCLoginViewController () <UIWebViewDelegate>
/// 用户名输入
@property (strong, nonatomic) IBOutlet UITextField *userNameTextField;
/// 密码输入
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
/// 登录按钮
@property (strong, nonatomic) IBOutlet UIButton *loginButton;
/// 关闭按钮
@property (strong, nonatomic) IBOutlet UIButton *closeButton;
/// 验证码图片View
@property (strong, nonatomic) IBOutlet UIImageView *captchaImageView;
/// 更换验证码
@property (strong, nonatomic) IBOutlet UILabel *changeCaptchaLabel;
/// 验证码输入
@property (strong, nonatomic) IBOutlet UITextField *captchaTextField;
/// 验证码框
@property (strong, nonatomic) IBOutlet UIView *captchaView;

@property (strong, nonatomic) UIWebView *webView;

@property (nonatomic, strong, readonly) OSCOAuthViewModel *viewModel;

@end

@implementation OSCLoginViewController

@dynamic viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES];
    [self.closeButton addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    [self.loginButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [self.webView loadRequest:[NSURLRequest requestWithURL:self.viewModel.oauthUrl]];
}
- (void)bindViewModel {
    [super bindViewModel];
    // 将值与输入框信号绑定
    RAC(self.viewModel.validationAccountParams,email) = self.userNameTextField.rac_textSignal;
    RAC(self.viewModel.validationAccountParams,pwd) = self.passwordTextField.rac_textSignal;
    RAC(self.viewModel.validationAccountParams,verifyCode) = self.captchaTextField.rac_textSignal;
    RAC(self.loginButton,enabled) = self.viewModel.enableLoginActive;
    @weakify(self);
    [[[RACObserve(self.viewModel, validationAccount)
      skip:1]
      filter:^BOOL(id value) {
          return [value boolValue];
      }]
    subscribeNext:^(NSNumber *validationAccount) {
        @strongify(self);
            // 用js将值传到webView上
            [self.webView stringByEvaluatingJavaScriptFromString:[self.viewModel stringForSetValue:self.viewModel.validationAccountParams.email ForJsTagById:js_email]];
            [self.webView stringByEvaluatingJavaScriptFromString:[self.viewModel stringForSetValue:self.viewModel.validationAccountParams.pwd ForJsTagById:js_password]];
            [self.webView stringByEvaluatingJavaScriptFromString:[self.viewModel stringForSetValue:self.viewModel.validationAccountParams.verifyCode ForJsTagById:js_captcha]];
            // 通过webView提交表单获取code
            [self.webView stringByEvaluatingJavaScriptFromString:self.viewModel.jsForRequestCode];
    }];
    [[RACObserve(self.viewModel, showCaptchaView)
     filter:^BOOL(id value) {
         return [value boolValue];
    }] subscribeNext:^(id x) {
        if (self.captchaView.hidden) {
            self.captchaView.hidden = NO;
        }
        [self loadCaptchaUrl];
    }];
}
- (void)close {
    [self.viewModel dismissViewModel];
}
- (void)login {
    [self.view endEditing:YES];
    // 将值通过js加密
    self.viewModel.validationAccountParams.pwd = [self.webView stringByEvaluatingJavaScriptFromString:[self.viewModel jsForEncryptionPassword:self.viewModel.validationAccountParams.pwd]];
    // 验证账户
    [self.viewModel.validationCommand execute:nil];
}
- (void)loadCaptchaUrl {
    // 拿到验证码随机路径
    NSString *image = [self.webView stringByEvaluatingJavaScriptFromString:self.viewModel.jsForCaptchaImageUrl];
    // 拼接
    NSString *urlStr = [kBaseURLStr stringByAppendingString:image];
    // 转urk
    NSURL *url = [NSURL URLWithString:urlStr];
    // 这里不能用SDWebImage去加载验证码,会多次调用url导致验证码图片错误
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *data = [[NSData alloc] initWithContentsOfURL:url];
        UIImage *captchaImage = [UIImage imageWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.captchaImageView.image = captchaImage;
        });
    });
}
#pragma mark - 懒加载
- (UIWebView *)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc] init];
        _webView.delegate = self;
    }
    return _webView;
}
#pragma mark - UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [self.loginButton setTitle:@"获取数据中" forState:UIControlStateNormal];
    self.loginButton.enabled = NO;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
    self.loginButton.enabled = YES;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *urlStr = request.URL.absoluteString;
    if (![urlStr hasPrefix:self.viewModel.oauthParams.redirect_uri]) {
        return YES;
    }
    // 拿code
    NSString *codeStr = @"code=";
    if ([request.URL.query hasPrefix:codeStr]) {
        NSRange rangeStart = [urlStr rangeOfString:codeStr];
        NSRange rangeEnd = [urlStr rangeOfString:@"&"];
        NSRange newRange = NSMakeRange(rangeStart.location + rangeStart.length, rangeEnd.location - (rangeStart.location + rangeStart.length));
        self.viewModel.oauthParams.code = [urlStr substringWithRange:newRange];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self.viewModel.tokenCommand execute:nil];
        });
    } else {
        [self close];
    }
    return NO;
}
@end
